import {
  getLogin,
  loginOut,
  autoLogin
} from "api/api"
import router from "router/router"
import { whiteList } from "@/util/config"

export default {
  state: {
    token:localStorage.getItem("sph_token"),
    userInfo:{}
  },
  getters: {
    
  },
  mutations: {
    getLogin(state,userInfo){
      state.userInfo = userInfo
    }
  },
  actions: {
    // 登录
    async getLogin(store,{phone,password,redirectUrl='/'}){
      // options:{phone,password}
      try{
        console.log(redirectUrl);
        const {code,data} = await getLogin({phone,password})
        console.log(code);
        if(code===200){
          localStorage.setItem("sph_token",data.token)
          let userInfo = {
            name:data.name,
            userId:data.userId
          }
          store.commit("getLogin",userInfo)
          console.log("111");
          await router.push(redirectUrl)
        }
        return {code}
      }catch(err){
        return Promise.reject(err)
      }
    },
    // 退出登录
    async loginOut(store,to=router.currentRoute){
      console.log(router.currentRoute.path);
      console.log(to);
      try{
        const {code} = await loginOut()
        if(code===200){
          localStorage.removeItem("sph_token")
          let userInfo={}
          store.commit("getLogin",userInfo)
          // 退出时，如果从非白名单组件退出，那么还是回到非白名单组件
          // 否则回到登录页
          let name = to.path.split("/")[1]
          if(whiteList.includes(name)){
            await router.push('/login')
          }else{
            if(name==='shopcart'){
              // 更新购物车
              await store.dispatch("getCartList")
            }
            await router.push(name)
          }
        }
        return {code}
      }catch(err){
        return Promise.reject(err)
      }
    },
    // 自动登录
    async autoLogin(store,to){
      try{
        const {code,data} = await autoLogin()
        if(code===200){
          // 登陆成功
          let userInfo = {
            name:data.name,
            userId:data.id
          }
          store.commit("getLogin",userInfo)
        }else{
          // 登陆失败，退出登录
          await store.dispatch("loginOut",to)
        }
        return {code}
      }catch(err){
        return Promise.reject(err)
      }
    }
  }
}
